﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Hzexe.Wechat.SharpSDK.Message.Response
{
    /// <summary>
    /// 响应消息基类
    /// </summary>
    public abstract class ResponseMessageBase:MessageBase
    { /// <summary>
        /// 消息类型与消息类的对应字典
        /// </summary>
        protected static Dictionary<string, Type> msgtypeDic;

        public ResponseMessageBase()
        { 
            //填充当前类型的MsgType值
            base.MsgType = msgtypeDic.SingleOrDefault(k => k.Value == this.GetType()).Key;
            base.CreateTime = DateTime.Now.ToFileTimeUtc().ToString();
        }
       

        static ResponseMessageBase()
        {
            msgtypeDic = new Dictionary<string, Type>(10);
            msgtypeDic.Add("text",typeof(Message_Out_Text));
            msgtypeDic.Add("image", typeof(Message_Out_Image));
            msgtypeDic.Add("location", typeof(Message_Out_Location));
            msgtypeDic.Add("link", typeof(Message_Out_Link));
            msgtypeDic.Add("news", typeof(Message_Out_News));
            msgtypeDic.Add("music", typeof(Message_Out_Music));
        }

        
        /// <summary>
        /// 已重载,把当前对象转换成xml字符串以输出,一般做调试用
        /// </summary>
        /// <returns>xml字符串</returns>
        public override string ToString()
        {
            var serializer = new XmlSerializer(this.GetType());
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.Serialize(ms, this, null);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            string xmlstr = System.Text.Encoding.UTF8.GetString(ms.ToArray());
            ms.Dispose();
            //因微信服务器不能识别带有命名空间的xml，崩溃
            xmlstr = System.Text.RegularExpressions.Regex.Replace(xmlstr, "<xml.*?>", "<xml>");
            xmlstr = System.Text.RegularExpressions.Regex.Replace(xmlstr, @"<\?xml.*?>", "");
            return xmlstr;
        }
    }
}
